<template>
  <div class="table-right-wrapper">
    <a-scrollbar ref="scrollbarRef" style="max-height: 63vh; overflow: auto; padding-bottom: 16px" @scroll="onScroll">
      <div class="header">
        <div
          class="date-item"
          :style="{ width: stockState.dayPx + 'px' }"
          :class="{ today: item.today }"
          v-for="item in stockState.dayList"
          :key="item.date"
        >
          {{ item.date }}
        </div>
      </div>
      <div class="body" :style="{ width: stockState.dayList.length * stockState.dayPx + 'px' }">
        <template v-for="group in stockState.stockData" :key="group.id">
          <!-- 车型格子 -->
          <div class="right-tr br"></div>
          <!-- 车牌和冲突占用的格子；使用background样式实现；是一个整体 -->
          <div
            class="grid right-tr"
            :style="{ height: `${group.columnNum * 40 + 1}px`, backgroundSize: `${stockState.dayPx}px 40px` }"
            @click="handleOperate($event, group)"
          >
            <template v-for="(column, carIndex) in group.columns" :key="carIndex">
              <!-- 占用格子，上下位置用的index实现 -->
              <FlyBar :data="bar" :carIndex="carIndex" v-for="bar in column" :key="bar.id" />
            </template>
          </div>
        </template>
        <!-- 操作 -->
        <a-popover v-model:popup-visible="operateTd.visible" trigger="click" position="bl" @popup-visible-change="popupVisibleChange">
          <template #content>
            <a-space direction="vertical">
              <a-button size="mini" v-permission="'svms:asstes:car:stock.platoonCar'" @click="platoonCar()">排车</a-button>
              <a-button size="mini" v-permission="'svms:asstes:car:stock.tempUse'" @click="addTempUse()">临时占用</a-button>
              <a-button size="mini" v-permission="'svms:asstes:car:stock.batchRemoveTempUse'" @click="removeTempUse()"
                >批量释放库存</a-button
              >
            </a-space>
          </template>
          <div
            @click.stop="closeOperate()"
            class="operate-td"
            :style="{ left: operateTd.left, top: operateTd.top, width: operateTd.width }"
          ></div>
        </a-popover>
      </div>
    </a-scrollbar>
  </div>

  <!-- 排车弹框 -->
  <PlatoonCarModal ref="platoonCarModalRef" />
  <!-- 临时占用弹框 -->
  <TempUseModal ref="tempUseModalRef" />
  <!-- 批量移除临时占用弹框 -->
  <removeTempUseModal ref="removeTempUseModalRef" />
</template>

<script lang="ts">
  import { ref, inject, computed, onActivated } from 'vue'
  import { usePermission } from '@/hooks/usePermission'
  import FlyBar from './widget/fly-bar.vue'
  import PlatoonCarModal from '../platoon-car-modal.vue'
  import TempUseModal from './widget/temp-use-modal.vue'
  import RemoveTempUseModal from './widget/remove-temp-use-modal.vue'

  export default {
    components: {
      FlyBar,
      PlatoonCarModal,
      TempUseModal,
      RemoveTempUseModal,
    },
    props: {
      data: Array,
    },
    setup() {
      const stockState = inject('stockState')
      const scrollbarRef = ref()

      onActivated(() => {
        setTimeout(() => {
          scrollbarRef.value.scrollTo({ left: stockState.scrollLeft, top: stockState.scrollTop })
        }, 100)
      })
      // 禁止弹出操作
      const isHandleRole = computed(() => {
        return !(
          !stockState.selector &&
          (usePermission('svms:asstes:car:stock.platoonCar') ||
            usePermission('svms:asstes:car:stock.tempUse') ||
            usePermission('svms:asstes:car:stock.batchRemoveTempUse'))
        )
      })

      // 文字气泡显示状态改变函数
      const popupVisibleChange = (visible) => {
        if (!visible) closeOperate()
      }

      // 滚动
      const onScroll = (event: Event) => {
        stockState.scrollTop = event.target.scrollTop
        stockState.scrollLeft = event.target.scrollLeft
        closeOperate()
      }

      // 操作
      const operateTd = ref({
        visible: false,
        left: '-1999px',
        top: '-1999px',
        width: '71px',
        car: null,
        group: null,
        date: null,
      })
      const handleOperate = (e: any, group: any) => {
        if (isHandleRole.value) return
        const dayWidth = stockState.dayPx
        const target = e.target
        const rect = target.getBoundingClientRect()
        // 向下取整获取车辆下标
        const carIndex = Math.floor(e.offsetY / 40)
        const car = group.car_columns[carIndex]
        // 冲突列禁止点击
        // if (!car.carId) {
        //   closeOperate()
        //   return
        // }

        const wrapper = document.querySelector('.table-right-wrapper .body').getBoundingClientRect()
        operateTd.value.top = rect.top - wrapper.top + carIndex * 40 + 1 + 'px'
        operateTd.value.visible = true
        operateTd.value.car = car
        operateTd.value.carModel = group
        const dateIndex = Math.floor(e.offsetX / dayWidth)
        operateTd.value.left = dateIndex * dayWidth + 'px'
        operateTd.value.width = dayWidth - 1 + 'px'

        const date = stockState.dayList[dateIndex]
        if (!date) {
          closeOperate()
          return
        }
        operateTd.value.date = date
      }
      const closeOperate = () => {
        operateTd.value.visible = false
        operateTd.value.left = '-1999px'
        operateTd.value.top = '-1999px'
      }

      const platoonCarModalRef = ref()
      // 排车
      const platoonCar = () => {
        const data = operateTd.value
        const params = {
          startDate: data.date.fullDate,
          carId: data.car.carId,
          licenseNo: data.car.licenseNo,
          carModelId: data.carModel.id,
          modelName: data.carModel.modelName,
        }
        platoonCarModalRef.value.open(params)
        closeOperate()
      }

      // 临时占用
      const tempUseModalRef = ref()
      const addTempUse = () => {
        const data = operateTd.value
        const params = {
          carId: data.car.carId,
          licenseNo: data.car.licenseNo,
          modelName: data.carModel.modelName,
        }
        tempUseModalRef.value.open(params)
        closeOperate()
      }

      // 批量移除临时占用
      const removeTempUseModalRef = ref()
      const removeTempUse = () => {
        const data = operateTd.value
        const params = {
          carId: data.car.carId,
          licenseNo: data.car.licenseNo,
          modelName: data.carModel.modelName,
        }
        removeTempUseModalRef.value.open(params)
        closeOperate()
      }

      return {
        operateTd,
        stockState,
        scrollbarRef,
        platoonCarModalRef,
        tempUseModalRef,
        removeTempUseModalRef,
        popupVisibleChange,
        isHandleRole,
        onScroll,
        platoonCar,
        addTempUse,
        removeTempUse,
        handleOperate,
        closeOperate,
      }
    },
  }
</script>

<style lang="less" scoped>
  @leftWidth: 120px;
  @tdWidth: 72px;
  @tdHeight: 40px;
  .table-right-wrapper {
    width: calc(100% - @leftWidth);
    margin-left: @leftWidth;
    position: relative;
    .header {
      position: sticky;
      top: 0;
      z-index: 20;
      width: fit-content;
      height: 40px;
      display: flex;
      overflow: hidden;
      flex-wrap: nowrap;
      background: #f2f3f5;
      border-bottom: 1px solid #e0e0e0;
      // width: 100%;
      .date-item {
        flex-shrink: 0;
        width: @tdWidth;
        border-right: 1px solid #e0e0e0;
        text-align: center;
        // 字
        line-height: 40px;
        font-size: 14px;
        font-weight: 600;
        color: #1d2129;

        &.today {
          color: #165dff;
        }
      }
    }
    .body {
      position: relative;
      z-index: 9;
      .right-tr {
        position: relative;
        display: flex;
        flex-wrap: nowrap;
        height: 39px;
        &.grid {
          background-image: linear-gradient(to right, #e0e0e0 1px, transparent 1px),
            linear-gradient(to bottom, #e0e0e0 1px, transparent 1px);
          background-size: @tdWidth @tdHeight;
          background-position: -1px 0;
          border-right: 1px solid #e0e0e0;
        }
      }
      .right-td {
        display: block;
        box-sizing: border-box;
        flex-shrink: 0;
        width: @tdWidth;
        background: #ffffff;
        border-right: 1px solid #e0e0e0;
      }
    }
  }

  .operate-td {
    height: @tdHeight - 1;
    width: @tdWidth - 1;
    background: rgba(232, 243, 255, 0.5);
    position: absolute;
    z-index: 999;
  }
</style>
